//
//  WONetworkCache.m
//  MedicalAlarmSystem
//
//  Created by 吴欧 on 2017/10/17.
//  Copyright © 2017年 吴欧. All rights reserved.
//

#import "WONetworkCache.h"
#import <YYCache.h>

static NSString *const kWONetworkResponseCache = @"kWONetworkResponseCache";

@implementation WONetworkCache
static YYCache *_dataCache;

+ (void)initialize {
    _dataCache = [YYCache cacheWithName:kWONetworkResponseCache];
}

+ (void)setHttpCache:(id)httpData URL:(NSString *)URL parameters:(NSDictionary *)parameters withBlock:(void (^)(void))block{
    NSString *cacheKey = [self cacheKeyWithURL:URL parameters:parameters];
    //异步缓存,不会阻塞主线程
    [_dataCache setObject:httpData forKey:cacheKey withBlock:block];
}

+ (id)httpCacheForURL:(NSString *)URL parameters:(NSDictionary *)parameters {
    NSString *cacheKey = [self cacheKeyWithURL:URL parameters:parameters];
    return [_dataCache objectForKey:cacheKey];
}

+ (NSInteger)getAllHttpCacheSize {
    return [_dataCache.diskCache totalCost];
}

+ (NSString *)getAllHttpCacheSizeForString {
    
    NSString *str = [NSString stringWithFormat:@"%.2fM",[_dataCache.diskCache totalCost] /1024.0/1024.0];
    NSArray *array = [str componentsSeparatedByString:@"."];
    
    if ([array[0] isEqualToString:@"0"]) {
        NSString *str_k = [NSString stringWithFormat:@"%.fKB",[_dataCache.diskCache totalCost] /1024.0];
        return str_k;
    }else {
        return str;
    }
}

+ (void)removeAllHttpCache {
    [_dataCache.diskCache removeAllObjects];
}

+ (void)removeAllHttpCacheWithBlock:(void(^)(void))block {
    [_dataCache.diskCache removeAllObjectsWithBlock:^{
        if (block) block();
    }];
}

+ (NSString *)cacheKeyWithURL:(NSString *)URL parameters:(NSDictionary *)parameters {
    if(!parameters || parameters.count == 0){return URL;};
    // 将参数字典转换成字符串
    NSData *stringData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
    NSString *paraString = [[NSString alloc] initWithData:stringData encoding:NSUTF8StringEncoding];
    NSString *cacheKey = [NSString stringWithFormat:@"%@%@",URL,paraString];
    
//    NSString *str = [NSString stringWithFormat:@"%ld",cacheKey.hash];
    
    return cacheKey;
}

@end
